package edu.fiu.cis.personalize.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import edu.fiu.cis.personalize.shared.FieldVerifier;
import edu.fiu.cis.personalize.shared.GoogleDocument;
import edu.fiu.cis.personalize.shared.QueryResult;
import edu.fiu.cis.personalize.shared.User;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PersonalizedSearch implements EntryPoint {

	private Button sendButton;

	private TextBox nameField;

	private Label errorLabel;

	private User user;

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final PersonalizedSearchServiceAsync searchService = GWT
			.create(PersonalizedSearchService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		sendButton = new Button("Search");
		nameField = new TextBox();
		nameField.setWidth("200px");
		errorLabel = new Label();

		String userIdStr = Window.Location.getParameter("uid");

		int userId = -1;
		try {
			userId = Integer.parseInt(userIdStr);
		} catch (Exception e) {

		}

		if (userId >= 0) {
			searchService.registerUser(userId,
					new DefaultAsyncCallback<User>() {
						@Override
						public void onSuccess(User result) {
							user = result;
							// We can add style names to widgets
							sendButton.addStyleName("sendButton");

							// Add the nameField and sendButton to the RootPanel
							// Use RootPanel.get() to get the entire body
							// element
							RootPanel.get("nameFieldContainer").add(nameField);
							RootPanel.get("sendButtonContainer")
									.add(sendButton);
							RootPanel.get("errorLabelContainer")
									.add(errorLabel);

							RootPanel.get("welcome").add(
									new WelcomeBar(user.getName(),
											"www.facebook.com",
											"www.google.com"));
							
							

							// Focus the cursor on the name field when the app
							// loads
							nameField.setFocus(true);

							// Add a handler to send the name to the server
							SearchHandler handler = new SearchHandler();
							sendButton.addClickHandler(handler);
							nameField.addKeyUpHandler(handler);
						}
					});
		} else {
			RootPanel.get("message").clear();
			RootPanel
					.get("message")
					.add(new HTML(
							"You must be logged into facebook to use this application. <a href=\"http://apps.facebook.com/fbpgoog\">Login</a> now."));
		}

	}

	private void submitQuery() {
		// First, we validate the input.
		errorLabel.setText("");
		String textToServer = nameField.getText();
		if (!FieldVerifier.isValidName(textToServer)) {
			errorLabel.setText(FieldVerifier.getErrorMessage(textToServer));
			return;
		}
		// Then, we send the input to the server.
		sendButton.setEnabled(false);
		searchService.search(user.getId(), textToServer,
				new DefaultAsyncCallback<QueryResult>() {
					public void onSuccess(QueryResult result) {
						VerticalPanel panel = new VerticalPanel();
						panel.setSpacing(5);
						RootPanel.get("container").clear();
						RootPanel.get("summary").clear();
						HTML sum = new HTML("Showing "
								+ result.getGoogleRanks().size()
								+ " results");
						RootPanel.get("summary").add(sum);
						RootPanel.get("container").add(panel);
						for (GoogleDocument document : result.getGoogleRanks()) {
							ResultDisplay anchor = new ResultDisplay(document,
									user, searchService, result.getQueryId());
							panel.add(anchor);
						}
						sendButton.setEnabled(true);
					}
				});

	}

	// Create a handler for the sendButton and nameField
	class SearchHandler implements ClickHandler, KeyUpHandler {
		/**
		 * Fired when the user clicks on the sendButton.
		 */
		public void onClick(ClickEvent event) {
			submitQuery();
		}

		/**
		 * Fired when the user types in the nameField.
		 */
		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
				submitQuery();
			}
		}
	}
}
